package com.tianjian.myblog.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 *
 * 全局异常拦截类
 *
 *
 */





@ControllerAdvice
public class ControllerExceptionHandler {

    //记录错误日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //注释说明拦截所有的异常相关类
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {

            logger.error("Request URL:{},Exception:{}",request.getRequestURI(),e);

            //凡是定义了被springboot处理的类这里不做处理（一些自定义异常）
            if(AnnotationUtils.findAnnotation(e.getClass(),ResponseStatus.class) != null) {
                throw e;
            }

            ModelAndView mv = new ModelAndView();
            mv.addObject("url",request.getRequestURI());
            mv.addObject("exception",e);
            mv.setViewName("error/error");
            return mv;

    }
}
